package com.cedifie.lendapp.ui.steps.act

import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.ActStepBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpAct
import com.cedifie.lendapp.ui.loan.act.CedLoanApplyAct
import com.cedifie.lendapp.ui.steps.adapter.CedStepTabAdapter
import com.cedifie.lendapp.ui.steps.fm.CedStepAccountFm
import com.cedifie.lendapp.ui.steps.fm.CedStepCommonFm
import com.cedifie.lendapp.ui.steps.fm.CedStepContactFm
import com.cedifie.lendapp.ui.steps.fm.CedStepFaceFm
import com.cedifie.lendapp.ui.steps.fm.CedStepOcrFm
import com.cedifie.lendapp.ui.steps.impl.CedStepPresenterImpl
import com.cedifie.lendapp.ui.steps.view.ICedStepView
import com.cedifie.lendapp.ui.user.act.CedUserFeedbackAct
import com.cedifie.lendapp.utils.ChooseContactUtils
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lib_baseadapter.CEDOnItemChildClickListener
import com.lib.base.utils.helper.ActivityStackManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/18 14:46
 * @Annotation：流程步骤
 */
class CedStepAct: MvpAct<ICedStepView, CedStepPresenterImpl>(),ICedStepView {
    private var _binding: ActStepBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )

    private var tabAdapter: CedStepTabAdapter? = null

    //选择联系人
    var chooseContact: ChooseContactUtils? = null
    override fun getCedRootView(): View {
        _binding = ActStepBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCedView() {
        setCedTitleBarVisibility(View.VISIBLE)
        setCedRightBtnRes(com.lib.base.R.mipmap.icon_kefu_black)
        setCedTextTitleGravity(Gravity.START)

        EventBus.getDefault().register(this)
        chooseContact = ChooseContactUtils(this)
        initCedRecyclerView()
    }

    override fun initCedListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(CedUserFeedbackAct::class.java)
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_CUSTOMER, "Information Process " + rootViewBinding.tvBaseTitle.text.toString() + " Page")
        }
    }

    override fun initCedData() {
        mvpPresenter?.loadCedProcessStepAction()
    }

    override fun createMvpPresenter(): CedStepPresenterImpl {
        return CedStepPresenterImpl(this)
    }

    /**
     * 初始化Tab列表
     */
    private fun initCedRecyclerView() {
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.recyclerView?.layoutManager = layoutManager
        tabAdapter = CedStepTabAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = tabAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        tabAdapter?.setOnItemChildClickListener(CEDOnItemChildClickListener { _, childView, _ ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        })
    }

    /**
     * 显示所有流程步骤
     */
    override fun showCedProcessStepList(stepList: ArrayList<JSONObject>, selectIndex: Int) {
        tabAdapter?.data = stepList
        if (selectIndex != -1) {
            setCedTextTitle(stepList[selectIndex].optString("tabTitle"))
            _binding?.recyclerView?.post {
                _binding?.recyclerView?.smoothScrollToPosition(selectIndex)
            }
        }
    }

    /**
     * 提交数据
     */
    fun onSubmitProcessAction(params: JSONObject){
        mvpPresenter?.onSubmitProcessAction(params)
    }

    /**
     * 进入贷款申请页面
     */
    override fun showCedLoanAppalyPage() {
        //避免多次跳转
        ActivityStackManager.finishActivity(CedLoanApplyAct::class.java)
        onIntent(CedLoanApplyAct::class.java)
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },500)
    }

    /**
     * 通用样式
     */
    override fun showCedStepCommonPage(data: JSONObject) {
        if (_binding == null){
            return
        }
        replaceContainerFragement(R.id.contentLayout, CedStepCommonFm(data))
    }

    /**
     * 联系人
     */
    override fun showCedStepContactPage(data: JSONObject) {
        if (_binding == null){
            return
        }
        replaceContainerFragement(R.id.contentLayout, CedStepContactFm(this,data))
    }

    /**
     * Ocr 样式
     */
    override fun showCedStepOcrPage() {
        if (_binding == null){
            return
        }
        replaceContainerFragement(R.id.contentLayout, CedStepOcrFm())
    }

    /**
     * 自拍照
     */
    override fun showCedStepSelfiePage() {
        if (_binding == null){
            return
        }
        replaceContainerFragement(R.id.contentLayout, CedStepFaceFm())
    }

    /**
     * 绑定账户（法语地区）
     */
    override fun showCedStepAccountPage() {
        if (_binding == null){
            return
        }
        replaceContainerFragement(R.id.contentLayout,CedStepAccountFm())
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    override fun showCedSubmitSuccess() {
        //通知刷新总流程
        EventBus.getDefault().post(CedEventType.NOTICE.CED_PROCESS_REFRESH)
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshedProcess(event: String){
        when(event){
            CedEventType.NOTICE.CED_PROCESS_REFRESHED -> {//总流程刷新完成
                mvpPresenter?.loadCedProcessStepAction()
            }
        }
    }

    override fun onStop() {
        super.onStop()
        _binding?.root?.clearFocus()
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        EventBus.getDefault().unregister(this)
    }
}